<template>
  <div class='wrapper'>
    <!-- header部分 -->
    <div style="height: 15vw;">
      <header>
        <p>我的信息</p>
      </header>
    </div>
    <ul class="user-information" style="margin-top: 10%;margin-bottom: 10%;">
      <li>
        <div class="user-information-img" style="margin-right: 5%;">
          <img src="../assets/userImg/userImg.png">
        </div>
        <div class="user-information-info">
          <h3>{{user.userName}}</h3>
          <p>{{user.userId}}</p>
          <p>{{showSex(user.userSex)}}</p>
        </div>
      </li>
    </ul>
    <div class="total" style="justify-content: space-between;display: flex;">
      <span class="h3" style="padding-left: 3%;">当前总积分:</span>
      <span style="display: flex;align-items: center;padding-right: 5%;">
        <span style="width: 50%;align-items: center;font-size: 8vw;">{{num}}</span>
        <span style="margin-left: 20%;align-items: center;"> <img src="../assets/jifen.png" width="50"
                                                                  height="25" style="align-items: center;margin-top: 5.5px;"></span>
      </span>
    </div>
    <div class="score-detail-title">
      <div class="h3" style="padding-left: 3%;">近五笔订单积分明细：</div>
      <div class="submenu"
           style="display: flex;align-items: center;padding-top: 5px;padding-bottom: 5px;justify-content: center;border-top:  1px solid black;">
        <div class="item">
          <div>所属订单</div>
        </div>
        <div class="item">
          <div>积分数量</div>
        </div>
        <div class="item">
          <div>获取日期</div>
        </div>
        <div class="item">
          <div>截止日期</div>
        </div>
      </div>
    </div>
    <!-- 积分明细内容 -->
    <ul class="score-detail-body">
      <li v-if="scoreArr.length" v-for="item in scoreArr" :key="item.scoreId">
        <div class="submenu" style="display: flex; padding-top: 5px; padding-bottom: 5px; justify-content: center;">
          <div class="item">
            <div>{{ item.orderId }}</div>
          </div>
          <div class="item">
            <div>{{ formatScore(item.scoreCount) }}</div>
          </div>
          <!-- 如果积分为正，显示获取和截止日期 -->
          <div v-if="item.scoreCount > 0" class="item">
            <div>{{ item.createDate }}</div>
          </div>
          <div v-if="item.scoreCount > 0" class="item">
            <div>{{ item.deadLine }}</div>
          </div>
          <!-- 如果积分为负，获取日期和截止日期为空，留空显示 -->
          <div  v-if="item.scoreCount < 0" class="item">
            <div></div>
          </div>
          <div v-if="item.scoreCount < 0" class="item">
            <div></div>
          </div>
        </div>
      </li>
      <li v-else>暂无积分明细</li> <!-- 如果没有积分明细 -->
    </ul>

    <div class="logout-and-merchant">
      <div class="merchant" @click="checkMerchantStatus">我是商家</div>
      <div class="logout" @click="logOut">退出登录</div>
    </div>
    <!--底部菜单部分-->
    <Footer></Footer>
  </div>
</template>

<script>
import {
  ref,
  onMounted, watch
} from 'vue';
import Footer from '../components/Footer.vue';
import axios from 'axios';
import qs from 'qs';
import {
  getSessionStorage
} from '@/common';
import {
  useRoute,
  useRouter
} from 'vue-router';

export default {
  name: 'Information',
  components: {
    Footer
  },
  methods: {
    formatScore(score) {
      return score > 0 ? `+${score}` : `${score}`;
    }
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const user = ref(getSessionStorage('user'));
    const information = ref(null);
    const scoreArr = ref([]);
    const num = ref(null);
    const isMerchant = ref(false); // 新增商家入驻状态
    const businessId = ref(null); // 商家ID

    const loading = ref(true);

    onMounted(() => {
      // 如果从支付页面返回，带有最新积分的参数
      if (route.query.updatedScore) {
        num.value = route.query.updatedScore;
      } else {
        // 否则，从后端获取最新积分总数
        axios.post('/ScoreController/getAllScore', null, {
          params: { userId: user.value.userId }
        })
            .then(response => {
              num.value = response.data;
            })
            .catch(error => {
              console.error(error);
            });
      }

      // 获取用户积分明细
      axios.post('/ScoreController/listScoreByUserId', qs.stringify({
        userId: user.value.userId
      }))
          .then(response => {
            console.log("Score List:", response.data); // 确保获得了正确的响应
            scoreArr.value = response.data.sort((a, b) => b.scoreId - a.scoreId).slice(0, 5);
          })
          .catch(error => {
            console.error("Error fetching score list:", error); // 打印错误信息
          });

    });

    watch(
        () => route.query.updatedScore,
        (newValue) => {
          if (newValue) {
            num.value = newValue;
            // 重新获取积分明细
            axios.post('/ScoreController/listScoreByUserId', qs.stringify({
              userId: user.value.userId
            }))
                .then(response => {
                  scoreArr.value = response.data.sort((a, b) => b.scoreId - a.scoreId).slice(0, 5);
                })
                .catch(error => {
                  console.error("Error fetching score list:", error);
                });
          }
        }
    );

    const logOut = () => {
      sessionStorage.removeItem('user');
      router.push({
        path: '/login'
      });
    };

    const showSex = (userSex) => {
      return userSex === 1 ? '男' : '女';
    };

    const checkMerchantStatus = () => {
      // 检查用户是否已经是商家
      axios
          .post("/MerchantController/checkMerchantStatus", qs.stringify({ userId: user.value.userId }))
          .then((response) => {
            const { isMerchant, businessId } = response.data;
            if (isMerchant) {
              // 如果已经注册商家，跳转到商家管理页面
              router.push({
                path: "/merchant/manage",
                query: { businessId },
              });
            } else {
              // 如果还没有注册，跳转到商家注册页面
              router.push({
                path: "/merchant/register",
              });
            }
          })
          .catch((error) => {
            console.error("获取商家状态失败", error);
          });
    };

    return {
      user,
      information,
      scoreArr,
      num,
      showSex,
      logOut,
      checkMerchantStatus
    };
  }
}
</script>


<style scoped>

.wrapper {
  height: 100vh; /* 使 wrapper 高度等于视口高度 */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}


.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097FF;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper .title {
  margin-top: 3vw;
  margin-bottom: 3vw;
  font-size: 6vw;
  text-align: center;
}

.wrapper .next-title {
  margin-top: 6vw;
  margin-bottom: 3vw;
  font-size: 6vw;
  text-align: center;
}

.wrapper .logout-and-merchant {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 10%;
  margin-bottom: 20%; /* 确保按钮与底部菜单不会重叠 */
}

.wrapper .logout {
  background-color: red;
  width: 80%;
  text-align: center;
  margin-top: 5%; /* 调整间距 */
  height: 8vw; /* 调整高度 */
  border-radius: 10px;
  font-size: 5vw;
  line-height: 8vw; /* 使行高等于高度，实现垂直居中 */
  padding: 0; /* 移除多余的内边距 */
  color: black; /* 将文字颜色改为白色 */
}


.wrapper .merchant {
  background-color: #FF9800;
  width: 80%; /* 宽度调整为80% */
  text-align: center;
  padding: 5%;
  border-radius: 10px;
  font-size: 5vw;
  color: white;
  cursor: pointer;
}

.wrapper .user-information li {
  display: flex;
  justify-content: center;
}

.wrapper .user-information li .user-information-img {
  position: relative;
}

.wrapper .user-information li .user-information-img img {
  border-radius: 100px;
}

.wrapper .user-information li .user-information-info {
  margin-left: 8vw;
}

.wrapper .user-information li .user-information-info h3 {
  font-size: 6vw;
  color: #555;
}

.wrapper .user-information li .user-information-info p {
  font-size: 6vw;
  color: #888;
  margin-top: 2vw;
}

.submenu {
  width: 96%;
  margin-left: 2%;
}

.wrapper .item {
  width: 24%;
  text-align: center;
  border-bottom: 1px solid black;
  font-size: 1.2em;
}

.wrapper .h3 {
  font-size: 1.5em;
  margin-block-start: 1em;
  margin-block-end: 1em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
  font-weight: bold;
}

.wrapper {
  overflow-x: hidden; /* 隐藏横向滚动条 */
}

body {
  margin: 0; /* 确保页面没有额外的间距 */
}

ul, li {
  padding: 0;
  margin: 0;
  list-style-type: none;
}

</style>